import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
const service = axios.create({
  // baseURL: 'https://api-hmzs.itheima.net/v1',
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 50000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 错误统一处理
    console.dir(error)
    if (error.response.status === 401) {
      // 删除token
      store.dispatch('user/logout')
      // 跳转登录页
      this.$router.push('/login')
    }

    Message.error(error.response.data.msg)
    return Promise.reject(error)
  }
)

export default service
